const { success, error, generateOrderNo, paginate, paginateResponse } = require('../utils/common');
const { sequelize } = require('../config/database');
const Order = require('../models/Order');
const Course = require('../models/Course');
const CourseUser = require('../models/CourseUser');
const logger = require('../utils/logger');

class PaymentController {
  /**
   * 创建支付订单
   */
  static createOrder = async (req, res) => {
    const { course_id, pay_type = 'alipay' } = req.body;

    if (!course_id) {
      return res.status(400).json(error('课程ID不能为空'));
    }

    // 检查课程是否存在
    const course = await Course.findOne({
      where: { id: course_id, status: 'published' }
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 检查是否已购买
    const existingPurchase = await CourseUser.findOne({
      where: { course_id, user_id: req.user.id }
    });

    if (existingPurchase) {
      return res.status(400).json(error('您已购买此课程'));
    }

    // 如果是免费课程，直接创建订单并完成
    if (course.is_free) {
      const order = await Order.create({
        order_no: generateOrderNo(),
        user_id: req.user.id,
        course_id,
        amount: 0,
        pay_amount: 0,
        pay_type: 'free',
        status: 'paid',
        pay_time: new Date()
      });

      // 创建课程用户关联
      await CourseUser.create({
        course_id,
        user_id: req.user.id,
        order_id: order.id,
        status: 'active'
      });

      // 增加课程学生数
      await course.increment('students_count');

      logger.info(`用户 ${req.user.id} 购买免费课程: ${course_id}`);

      res.json(success({ order_id: order.id }, '购买成功'));
      return;
    }

    // 创建付费订单
    const order = await Order.create({
      order_no: generateOrderNo(),
      user_id: req.user.id,
      course_id,
      amount: course.price,
      pay_type
    });

    logger.info(`用户 ${req.user.id} 创建订单: ${order.order_no}`);

    // TODO: 根据支付方式生成支付链接
    let payUrl = '';
    if (pay_type === 'alipay') {
      payUrl = await PaymentController.createAlipayOrder(order);
    } else if (pay_type === 'wechat') {
      payUrl = await PaymentController.createWechatOrder(order);
    }

    res.json(success({
      order_id: order.id,
      order_no: order.order_no,
      amount: order.amount,
      pay_url: payUrl
    }, '订单创建成功'));
  };

  /**
   * 支付回调处理
   */
  static paymentCallback = async (req, res) => {
    const { order_no, trade_no, pay_type } = req.body;

    if (!order_no || !trade_no) {
      return res.status(400).json(error('参数不完整'));
    }

    // 查找订单
    const order = await Order.findOne({
      where: { order_no, status: 'pending' }
    });

    if (!order) {
      return res.status(404).json(error('订单不存在'));
    }

    // 验证支付结果
    let isValid = false;
    if (pay_type === 'alipay') {
      isValid = await PaymentController.verifyAlipayPayment(req.body);
    } else if (pay_type === 'wechat') {
      isValid = await PaymentController.verifyWechatPayment(req.body);
    }

    if (!isValid) {
      return res.status(400).json(error('支付验证失败'));
    }

    // 更新订单状态
    await order.update({
      status: 'paid',
      pay_amount: order.amount,
      pay_time: new Date(),
      trade_no
    });

    // 创建课程用户关联
    await CourseUser.create({
      course_id: order.course_id,
      user_id: order.user_id,
      order_id: order.id,
      status: 'active'
    });

    // 增加课程学生数
    await Course.increment('students_count', {
      where: { id: order.course_id }
    });

    logger.info(`订单支付成功: ${order_no}`);

    res.json(success(null, '支付成功'));
  };

  /**
   * 获取订单列表
   */
  static getOrders = async (req, res) => {
    const { page = 1, limit = 10, status } = req.query;

    const where = { user_id: req.user.id };
    if (status) where.status = status;

    const { offset, limit: pageLimit } = paginate(page, limit);

    const { count, rows } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: Course,
          attributes: ['id', 'title', 'cover', 'price']
        }
      ],
      offset,
      limit: pageLimit,
      order: [['created_at', 'DESC']]
    });

    res.json(paginateResponse(rows, count, page, limit));
  };

  /**
   * 获取订单详情
   */
  static getOrderDetail = async (req, res) => {
    const { id } = req.params;

    const order = await Order.findOne({
      where: { id, user_id: req.user.id },
      include: [
        {
          model: Course,
          attributes: ['id', 'title', 'cover', 'price', 'description']
        }
      ]
    });

    if (!order) {
      return res.status(404).json(error('订单不存在'));
    }

    res.json(success(order, '获取成功'));
  };

  /**
   * 取消订单
   */
  static cancelOrder = async (req, res) => {
    const { id } = req.params;

    const order = await Order.findOne({
      where: { id, user_id: req.user.id, status: 'pending' }
    });

    if (!order) {
      return res.status(404).json(error('订单不存在或无法取消'));
    }

    await order.update({ status: 'cancelled' });

    logger.info(`用户 ${req.user.id} 取消订单: ${order.order_no}`);

    res.json(success(null, '订单已取消'));
  };

  /**
   * 申请退款
   */
  static refundOrder = async (req, res) => {
    const { id } = req.params;
    const { reason } = req.body;

    const order = await Order.findOne({
      where: { id, user_id: req.user.id, status: 'paid' }
    });

    if (!order) {
      return res.status(404).json(error('订单不存在或无法退款'));
    }

    // TODO: 调用第三方支付平台退款接口
    await order.update({ status: 'refunded' });

    logger.info(`用户 ${req.user.id} 申请退款: ${order.order_no}`);

    res.json(success(null, '退款申请已提交'));
  };

  /**
   * 创建支付宝订单
   */
  static async createAlipayOrder(order) {
    // TODO: 集成支付宝SDK
    logger.info(`创建支付宝订单: ${order.order_no}`);
    return `https://openapi.alipay.com/gateway.do?order_no=${order.order_no}`;
  }

  /**
   * 创建微信支付订单
   */
  static async createWechatOrder(order) {
    // TODO: 集成微信支付SDK
    logger.info(`创建微信支付订单: ${order.order_no}`);
    return `https://pay.weixin.qq.com/pay?order_no=${order.order_no}`;
  }

  /**
   * 验证支付宝支付
   */
  static async verifyAlipayPayment(paymentData) {
    // TODO: 验证支付宝支付结果
    return true;
  }

  /**
   * 验证微信支付
   */
  static async verifyWechatPayment(paymentData) {
    // TODO: 验证微信支付结果
    return true;
  }
}

module.exports = PaymentController; 